package com.mytool.controller;

import com.mytool.model.GenerateCodeReq;
import com.mytool.service.GenerateCodeService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 代码生成器控制器
 */
@Controller
@RequestMapping("/generator")
@Slf4j
public class DdlGenerateController {

    @Autowired
    GenerateCodeService generateCodeService;

    /**
     * 显示代码生成器页面
     */
    @GetMapping
    public String showGeneratorPage(Model model) {
        GenerateCodeReq input = new GenerateCodeReq();
        input.setFrameworkType("call_db"); // 默认使用Spring Boot 3.3.0架构
        model.addAttribute("input", input);
        return "generator";
    }

    /**
     * 处理DDL生成请求
     */
    @PostMapping
    public String generateColaCode(HttpServletResponse response, GenerateCodeReq input, Model model) {
//        log.info(input.getDdlSql());
        byte[] data = generateCodeService.zipContent(input);
        genCode(response, data);
        return "ok";
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) {
        try {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            StreamUtils.copy(data, response.getOutputStream());
        } catch (Exception e) {
            log.error("download zip error.", e);
        }
    }
}
